package com.briup.cart.service.impl;

import com.briup.api.client.ItemClient;
import com.briup.api.po.Goods;
import com.briup.cart.config.CartProperties;
import com.briup.cart.domain.vo.ShopCarGetListVO;
import com.briup.cart.mapper.ShopcarMapper;
import com.briup.cart.service.ShopcarService;
import com.briup.common.exception.SystemException;
import com.briup.common.response.CodeAndMessageEnum;
//import com.briup.common.utils.SystemUtils;
import com.briup.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author qinyc
 * @description 针对表【es_shopcar(购物车表)】的数据库操作Service实现
 * @createDate 2024-12-24 09:16:52
 */
@Service
@RequiredArgsConstructor
public class ShopcarServiceImpl implements ShopcarService {

    @Autowired
    private ShopcarMapper shopcarMapper;
//    @Autowired
//    private SystemUtils systemUtils;
//    @Autowired
//    private RestTemplate restTemplate;
//    @Autowired
//    private DiscoveryClient discoveryClient;
    @Autowired
    private ItemClient itemClient;

    //添加配置类对象
    private final CartProperties cartProperties;

    @Override
    public Integer getCount(Integer userId) {
        Integer count = shopcarMapper.count(userId);
        return count;
    }

    @Override
    public void addShopCar(Integer goodsId, Integer num) {
        //1.获取登录用户
        Integer userId = UserContext.getUser();

        //2.判断商品是否已经存在
        List<ShopCarGetListVO> shopCarList = shopcarMapper.getListByUserId(userId);
        if(shopCarList != null && shopCarList.size() > 0) {
            for (ShopCarGetListVO shopCarGetListVO : shopCarList) {
                //2.1 商品已经存在，更新其数量
                if (shopCarGetListVO.getGoodsId().equals(goodsId)) {
                    int total = shopCarGetListVO.getNum() + num;
                    shopcarMapper.updateNum(shopCarGetListVO.getId(), total);

                    return;
                }
            }
        }

        //2.2 商品不存在，先判断购物车数量 是否 已经超过最大值
        checkCartsFull(userId);

        // 2.3 商品不存在，添加到购物车
        shopcarMapper.insert(UserContext.getUser(), goodsId, num);
    }

    //判断购物车是否已满
    private void checkCartsFull(Integer userId) {
        //获取指定用户购物车商品种类 数量
        long count = shopcarMapper.count(userId);
        //System.out.println("购物车商品种类数量：" + count);
        int maxNum = cartProperties.getMaxItems();
        System.out.println("maxNum: " + maxNum);
        if (count >= maxNum) {
            throw new SystemException(CodeAndMessageEnum.SHOP_CAR_IS_FULL);
        }
    }

    @Override
    public List<ShopCarGetListVO> getList() {
//        return shopcarMapper.getListByUserId(SystemUtils.getCurrentUserId());
        //1.查询指定用户购物车中信息
        List<ShopCarGetListVO> shopcars = shopcarMapper.getListByUserId(UserContext.getUser());
        //System.out.println("补全商品信息前，shopcars: " + shopcars);

        //2.获取购物车中所有商品的id
        List<Integer> goodIds = shopcars.stream().map(ShopCarGetListVO::getGoodsId)
                                                .collect(Collectors.toList());

        //3.根据ids查询商品信息
        List<Goods> goods = itemClient.queryItemByIds(goodIds);
        if(CollectionUtils.isEmpty(goods)) {
            return shopcars;
        }

        //4.补全购物车中商品的相关信息(图片、价格、名称)
        Map<Integer, Goods> goodsMap =
                goods.stream().collect(Collectors.toMap(Goods::getId, Function.identity()));
        shopcars.forEach(shopCarGetListVO -> {
            Goods g = goodsMap.get(shopCarGetListVO.getGoodsId()); // 通过 goodsId 快速查找 Goods 对象
            if (g != null) {
                shopCarGetListVO.setCover(g.getCover());
                //商品在购物车中的数量
                shopCarGetListVO.setNum(shopCarGetListVO.getNum());
                //System.out.println("g.getStoreNum(): " + g.getStoreNum());
                shopCarGetListVO.setPrice(g.getPrice());
                shopCarGetListVO.setName(g.getName());
            }
        });
        //System.out.println("补全商品信息后，shopcars: " + shopcars);

        return shopcars;
    }

    @Override
    public void updateNum(Integer id, Integer num) {
        /**
         * 参数校验
         */
        if (Objects.isNull(id)) {
            throw new SystemException(CodeAndMessageEnum.SHOP_CAR_ID_IS_NULL);
        }
        if (num < 1) {
            throw new SystemException(CodeAndMessageEnum.SHOP_CAR_NUM_IS_ERROR);
        }

        shopcarMapper.updateNum(id, num);
    }

    @Override
    public void batchDelete(List<Integer> ids) {
        /**
         * 参数校验
         */
        //根据ID查询购物车信息是否存在
        List<Integer> existIds = shopcarMapper.selectById(ids);

        //获取不存在的ID
        ids.removeAll(existIds);

        if (!ids.isEmpty()) {
            throw new SystemException(CodeAndMessageEnum.SHOP_CAR_IDS_IS_ERROR);
        }

        shopcarMapper.delete(existIds);
    }
}




